package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.cac409club.common.exception.ResultCodeConstant;
import com.example.cac409club.mapper.UserMapper;
import com.example.cac409club.result.RestResult;
import com.example.mapper.ClubMemberMapper;
import com.example.model.dos.ClubMemberDO;
import com.example.model.dto.ClubMemberDTO;
import com.example.model.query.ClubMemberQuery;
import com.example.service.ClubMemberService;
import com.example.utils.FileUtils;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 社团成员信息管理服务实现
 * </p>
 * @author 34448
 */
@Service
public class ClubMemberServiceImpl implements ClubMemberService {

    @Autowired
    private ClubMemberMapper clubMemberMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public RestResult<Boolean> addClubMember(ClubMemberDTO clubMemberDTO) {
        // 检查用户是否存在
        if (userMapper.selectById(clubMemberDTO.getUserId()) == null) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }

        // 检查社团成员信息是否已存在
        QueryWrapper<ClubMemberDO> wrapper = Wrappers.query();
        wrapper.eq("user_id", clubMemberDTO.getUserId());
        ClubMemberDO existingMember = clubMemberMapper.selectOne(wrapper);
        if (existingMember != null) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, "社团成员信息已存在");
        }

        ClubMemberDO clubMemberDO = new ClubMemberDO();
        BeanUtils.copyProperties(clubMemberDTO, clubMemberDO);
        clubMemberDO.setCreateTime(new Date());
        clubMemberDO.setUpdateTime(new Date());
        return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG,
                clubMemberMapper.insert(clubMemberDO) > 0);
    }

    @Override
    @Transactional
    public RestResult<Boolean> editClubMember(ClubMemberDTO clubMemberDTO) {
        // 检查社团成员信息是否存在
        ClubMemberDO existingMember = clubMemberMapper.selectById(clubMemberDTO.getMemberId());
        if (existingMember == null) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, "社团成员信息不存在");
        }

        // 更新社团成员信息
        BeanUtils.copyProperties(clubMemberDTO, existingMember);
        existingMember.setUpdateTime(new Date());
        return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG,
                clubMemberMapper.updateById(existingMember) > 0);
    }

    @Override
    @Transactional
    public RestResult<Boolean> deleteClubMember(ClubMemberQuery clubMemberQuery) {
        // 检查社团成员信息是否存在
        ClubMemberDO existingMember = clubMemberMapper.selectById(clubMemberQuery.getMemberId());
        if (existingMember == null) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, "社团成员信息不存在");
        }

        // 删除社团成员信息
        return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG,
                clubMemberMapper.deleteById(clubMemberQuery.getMemberId()) > 0);
    }

    @Override
    public RestResult<ClubMemberDO> getClubMemberInfo(ClubMemberQuery clubMemberQuery) {
        // 检查查询参数
        if (clubMemberQuery.getMemberId() == null && clubMemberQuery.getUserId() == null) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, "查询参数错误");
        }

        // 根据输入参数查询社团成员信息
        QueryWrapper<ClubMemberDO> wrapper = Wrappers.query();
        if (clubMemberQuery.getMemberId() != null) {
            wrapper.eq("member_id", clubMemberQuery.getMemberId());
        } else {
            wrapper.eq("user_id", clubMemberQuery.getUserId());
        }

        ClubMemberDO clubMemberDO = clubMemberMapper.selectOne(wrapper);
        if (clubMemberDO == null) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, "社团成员信息不存在");
        }

        return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG, clubMemberDO);
    }

    @Override
    @Transactional
    public RestResult<Boolean> importClubMemberInfo(String filePath) {
        // 检查文件路径是否有效
        if (!FileUtils.isValidFilePath(filePath)) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, "文件路径无效");
        }

        try {
            // 解析文件并导入社团成员信息
            List<ClubMemberDO> members = FileUtils.parseClubMembersFromFile(filePath);
            for (ClubMemberDO member : members) {
                clubMemberMapper.insert(member);
            }
            return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG);
        } catch (IOException e) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, "文件解析失败");
        }
    }

    @Override
    @Transactional
    public RestResult<Boolean> exportClubMemberInfo(String filePath) {
        // 检查文件路径是否有效
        if (!FileUtils.isValidFilePath(filePath)) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, "文件路径无效");
        }

        try {
            // 查询所有社团成员信息
            List<ClubMemberDO> members = clubMemberMapper.selectList(null);
            // 导出社团成员信息到指定文件路径
            FileUtils.exportClubMembersToFile(members, filePath);
            return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG);
        } catch (IOException e) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, "文件导出失败");
        }
    }

    @Override
    @Transactional
    public RestResult<Boolean> uploadClubMemberPhoto(Integer userId, MultipartFile file) {
        // 检查用户是否存在
        if (userMapper.selectById(userId) == null) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }

        // 保存文件并更新社团成员照片URL
        try {
            String photoUrl = FileUtils.saveFile(file, "photos");
            ClubMemberDO clubMemberDO = clubMemberMapper.selectOne(Wrappers.query().eq("user_id", userId));
            if (clubMemberDO == null) {
                return new RestResult<>(ResultCodeConstant.CODE_000001, "社团成员信息不存在");
            }
            clubMemberDO.setPhotoUrl(photoUrl);
            clubMemberDO.setUpdateTime(new Date());
            clubMemberMapper.updateById(clubMemberDO);
            return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG);
        } catch (IOException e) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, "文件上传失败");
        }
    }

    @Override
    @Transactional
    public RestResult<Boolean> uploadClubMemberCertificate(Integer userId, MultipartFile file) {
        // 检查用户是否存在
        if (userMapper.selectById(userId) == null) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }

        // 保存文件并更新社团成员证书URL
        try {
            String certificateUrl = FileUtils.saveFile(file, "certificates");
            ClubMemberDO clubMemberDO = clubMemberMapper.selectOne(Wrappers.query().eq("user_id", userId));
            if (clubMemberDO == null) {
                return new RestResult<>(ResultCodeConstant.CODE_000001, "社团成员信息不存在");
            }
            clubMemberDO.setCertificateUrl(certificateUrl);
            clubMemberDO.setUpdateTime(new Date());
            clubMemberMapper.updateById(clubMemberDO);
            return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG);
        } catch (IOException e) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, "文件上传失败");
        }
    }
}